<template>
  <div>
    <div class="sky-screen ivu-mb-16">
      <DatePicker
        :editable="false"
        type="daterange"
        :transfer="true"
        v-model="datepick"
        placeholder="回访日期"
        @on-change="changedate"
      ></DatePicker>
    </div>
    <div class="sky-note">
      <ButtonGroup>
        <Button
          :type="stateswitchs === '' ? 'primary' : 'default'"
          @click="stateswitch('')"
          >全部</Button
        >
        <Button
          :type="
            stateswitchs === item.callback_status_name ? 'primary' : 'default'
          "
          @click="stateswitch(item.callback_status_name)"
          v-for="(item, index) in list.total_arr"
          :key="index"
          >{{ item.callback_status_name }}({{ item.total }})</Button
        >
      </ButtonGroup>
      <Checkbox class="ivu-ml-16" @on-change="haveMark">有批注</Checkbox>
    </div>

    <div>
      <Timeline
        v-if="allDatas.length"
        class="ivu-pt-16"
        style="max-height: 420px; overflow: auto"
      >
        <template v-for="(item, index) in allDatas">
          <TimelineItem :key="index" v-if="stateswitchs === ''">
            <p class="time">{{ item.created_at }}</p>
            <p class="content" v-if="+item.data_type === 1">
              {{ item.content }}
            </p>
            <div
              class="content"
              v-else-if="+item.data_type === 2"
              style="display: flex;flex-direction: column;"
            >
              <span v-if="item.callback_id > 0 && item.duration > 0">{{
                item.callback_content
              }}</span>
              <p style="display: flex;align-items:center;">
                <audio
                  :id="`audio-${item.id}`"
                  v-if="item.file_url"
                  controls
                  preload="none"
                  controlsList="nodownload"
                  :src="item.file_url"
                  @play="audioplays(item.speed, item.id)"
                ></audio>
                <span v-if="item.file_url != ''" class="ivu-ml-16">
                  播放倍速：
                  <RadioGroup
                    v-model="item.speed"
                    @on-change="changeaudio(item.speed, item.id)"
                  >
                    <Radio
                      :label="items.id"
                      v-for="items in RadioGroup"
                      :key="items.id"
                      >{{ items.name }}</Radio
                    >
                  </RadioGroup>
                </span>
              </p>
            </div>
            <p class="consultant">
              <span class="ivu-mr-8" v-if="item.profession_name">{{
                item.profession_name
              }}</span>
              <span class="ivu-mr-8" v-if="item.member_name">{{
                item.member_name
              }}</span>
              <Badge
                status="processing"
                :text="item.callback_status_name"
                v-if="item.callback_status_name"
                class="ivu-mr-8"
              ></Badge>
              <Badge
                class="ivu-mr-8"
                status="warning"
                v-if="item.callback_way_name"
                :text="item.callback_way_name"
              ></Badge>
              <span v-if="item.duration">{{ item.duration }}秒</span>
              <Icon
                @click="changeupdate(item)"
                v-if="
                  ((+item.data_type === 2 && +item.type === 1) ||
                    +item.type === 2) &&
                    item.file_url == '' &&
                    item.duration !== ''
                "
                class="ivu-ml-8 icon"
                type="md-sync"
                color="#19be6b"
                size="18"
              ></Icon>
              <span
                class="pizhu"
                v-hasC="{
                  name: 'v1-patient-index-add-comment',
                  flag: 'v1/patient/index/add-comment',
                }"
                v-if="!item.comment"
                @click="openRemark(item, 'add')"
                >批注</span
              >
            </p>
            <div class="remark" v-if="item.comment">
              <p v-html="item.comment.replaceAll('\n', '<br>')"></p>
              <p>
                <span>{{ item.comment_name }}</span>
                <span>{{ item.comment_time }}</span>
                <span
                  v-hasC="{
                    name: 'v1-patient-index-update-comment',
                    flag: 'v1/patient/index/update-comment',
                  }"
                  @click="openRemark(item, 'update')"
                  >编辑</span
                ><Divider type="vertical"></Divider>
                <span
                  v-hasC="{
                    name: 'v1-patient-index-del-comment',
                    flag: 'v1/patient/index/del-comment',
                  }"
                  @click="delRemark(item)"
                  >删除</span
                >
              </p>
            </div>
          </TimelineItem>
          <TimelineItem
            :key="index"
            v-else-if="
              item.callback_way_name === stateswitchs ||
                item.callback_status_name === stateswitchs
            "
          >
            <p class="time">{{ item.created_at }}</p>
            <p class="content" v-if="+item.data_type === 1">
              {{ item.content }}
            </p>
            <p
              class="content"
              v-else-if="+item.data_type === 2"
              style="display: flex;align-items: center;"
            >
              <audio
                :id="`audio-${item.id}`"
                v-if="item.file_url"
                controls
                :src="item.file_url"
                @play="audioplays(item.speed, item.id)"
              ></audio>
              <span v-if="item.file_url != ''" class="ivu-ml-16">
                播放倍速：
                <RadioGroup
                  v-model="item.speed"
                  @on-change="changeaudio(item.speed, item.id)"
                >
                  <Radio
                    :label="items.id"
                    v-for="items in RadioGroup"
                    :key="items.id"
                    >{{ items.name }}</Radio
                  >
                </RadioGroup>
              </span>
            </p>
            <p class="consultant">
              <span class="ivu-mr-8" v-if="item.profession_name">{{
                item.profession_name
              }}</span>
              <span class="ivu-mr-8" v-if="item.member_name">{{
                item.member_name
              }}</span>
              <Badge
                status="processing"
                :text="item.callback_status_name"
                v-if="item.callback_status_name"
                class="ivu-mr-8"
              ></Badge>
              <Badge
                class="ivu-mr-8"
                status="warning"
                v-if="item.callback_way_name"
                :text="item.callback_way_name"
              ></Badge>
              <span v-if="item.duration">{{ item.duration }}秒</span>
              <Icon
                @click="changeupdate(item)"
                v-if="
                  ((+item.data_type === 2 && +item.type === 1) ||
                    +item.type === 2) &&
                    item.file_url == '' &&
                    item.duration !== ''
                "
                class="ivu-ml-8 icon"
                type="md-sync"
                color="#19be6b"
                size="18"
              ></Icon>
              <span
                class="pizhu"
                v-hasC="{
                  name: 'v1-patient-index-add-comment',
                  flag: 'v1/patient/index/add-comment',
                }"
                v-if="!item.comment"
                @click="openRemark(item, 'add')"
                >批注</span
              >
            </p>
            <div class="remark" v-if="item.comment">
              <p v-html="item.comment.replaceAll('\n', '<br>')"></p>
              <p>
                <span>{{ item.comment_name }}</span>
                <span>{{ item.comment_time }}</span>
                <span
                  v-hasC="{
                    name: 'v1-patient-index-update-comment',
                    flag: 'v1/patient/index/update-comment',
                  }"
                  @click="openRemark(item, 'update')"
                  >编辑</span
                ><Divider type="vertical"></Divider>
                <span
                  v-hasC="{
                    name: 'v1-patient-index-del-comment',
                    flag: 'v1/patient/index/del-comment',
                  }"
                  @click="delRemark(item)"
                  >删除</span
                >
              </p>
            </div>
          </TimelineItem>
        </template>
      </Timeline>
      <div
        v-else
        style="
              width: 100%;
              height: 200px;
              display: flex;
              align-items: center;
              justify-content: center;
            "
      >
        <span>暂无数据</span>
      </div>
    </div>
    <Modal v-model="modal" footer-hide>
      <p style="text-align: center;font-size:16px">
        录音同步已提交，请两分钟后刷新页面查看
      </p>
    </Modal>

    <Modal
      v-model="showMark"
      :closable="false"
      title="批注"
      draggable
      :mask-closable="false"
    >
      <Form :model="remarkParams" ref="formItem" :rules="ruleValidate">
        <FormItem label="" prop="comment">
          <Input
            type="textarea"
            placeholder="请输入批注内容"
            v-model="remarkParams.comment"
            :autosize="{ minRows: 4, maxRows: 8 }"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="canceledit">取消</Button>
        <Button :loading="markloading" @click="saveRemark" type="primary"
          >确认</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  patientindexcallbacklist,
  createvoiceQueue,
  addComment,
  updateComment,
  delComment,
} from "@/api/hqapi";
// import template from '../search/template.vue';
export default {
  // components: { template },
  props: ["id"],
  data() {
    return {
      loading: false,
      markloading: false,
      showMark: false,
      params: {
        start_time: "",
        end_time: "",
        patient_user_id: "",
        page: 0,
        pageSize: 0,
      },
      RadioGroup: [
        { id: 0.5, name: "0.5" },
        { id: 0.75, name: "0.75" },
        { id: 1, name: "1.0" },
        { id: 1.5, name: "1.5" },
        { id: 1.75, name: "1.75" },
        { id: 2, name: "2.0" },
      ],
      datepick: ["", ""],
      list: {},
      allDatas: [],
      stateswitchs: "",
      keyList: 0,
      audioplay: null,
      speedid: null,
      modal: false,
      state: true,
      remarkParams: {
        comment: "",
        relation_id: "",
        type: "",
      },
      remarkAct: "add",
      ruleValidate: {
        comment: [
          {
            required: true,
            message: "请输入批注内容",
            trigger: "change",
          },
        ],
      },
    };
  },
  // watch: {
  //   id: {
  //     handler(value) {
  //       if (value) {
  //         this.$nextTick(() => {
  //           this.askData(value);
  //         });
  //       }
  //     },
  //     deep: true,
  //     immediate: true,
  //   },
  // },
  methods: {
    openRemark(data, act) {
      this.$refs["formItem"].resetFields();
      this.remarkParams.comment = data.comment;
      this.remarkParams.relation_id = data.id;
      this.remarkParams.type = data.data_type;
      this.remarkAct = act;
      this.showMark = true;
    },
    canceledit() {
      (this.remarkParams = {
        comment: "",
        relation_id: "",
        type: "",
      }),
        (this.showMark = false);
    },
    delRemark(data) {
      this.$Modal.confirm({
        title: "删除确认",
        content: "<p>确定删除这条批注？</p>",
        loading: true,
        onOk: () => {
          delComment({ relation_id: data.id, type: data.data_type }).then(
            (res) => {
              this.askDatas();
              this.$Modal.remove();
            }
          );
        },
      });
    },
    saveRemark() {
      this.$refs["formItem"].validate((valid) => {
        if (valid) {
          this.markloading = true;
          if (this.remarkAct == "add") {
            addComment(this.remarkParams)
              .then((res) => {
                this.markloading = false;
                this.askDatas();
                this.canceledit();
              })
              .catch((e) => {
                this.markloading = false;
              });
          } else {
            updateComment(this.remarkParams)
              .then((res) => {
                this.markloading = false;
                this.askDatas();
                this.canceledit();
              })
              .catch((e) => {
                this.markloading = false;
              });
          }
        }
      });
    },
    changeupdate(item) {
      if (this.state) {
        this.state = false;
        let time = item.created_at.trim().split(" ");
        const params = {
          wechatid: item.wechatid,
          imei: item.deviceid,
          start_time: `${time[0]} 00:00:00`,
          end_time: `${time[0]} 23:59:59`,
          type: "swoole",
        };
        createvoiceQueue(params)
          .then((res) => {
            this.modal = true;
            setTimeout(() => {
              this.state = true;
            }, 180000);
          })
          .catch(() => {
            this.modal = false;
          });
      }
    },
    haveMark(e) {
      this.params.is_comment = e ? 1 : 0;
      this.askDatas();
    },
    askData(id) {
      this.list = {};
      this.data = [];
      this.datepick = ["", ""];
      (this.params = {
        start_time: "",
        end_time: "",
        patient_user_id: id,
        page: 0,
        pageSize: 0,
        is_comment: 0,
      }),
        this.askDatas();
    },
    askDatas() {
      patientindexcallbacklist(this.params).then((res) => {
        this.list = res;
        let list = [];
        for (let item of res.list.list) {
          list.push({ ...item, speed: 1 });
        }
        setTimeout(() => {
          this.allDatas = list;
        }, 60);
      });
    },
    stateswitch(name) {
      this.stateswitchs = name;
    },
    changedate() {
      this.params.start_time = this.datepick[0];
      this.params.end_time = this.datepick[1];
      this.askDatas();
    },
    changeaudio(speed, id) {
      if (this.speedid === id) {
        this.audioplay.playbackRate = speed;
      }
    },
    audioplays(speed, id) {
      if (this.audioplay) {
        if (this.speedid !== id) {
          this.audioplay.pause();
          this.audioplay = null;
        }
      }
      this.speedid = id;
      this.audioplay = document.getElementById(`audio-${id}`);
      // console.log(speed, id)
      // console.log(this.audioplay)
      this.audioplay.playbackRate = speed;
    },
  },
  destroyed() {
    if (this.audioplay) this.audioplay.pause();
  },
};
</script>
<style scoped>
.time {
  font-size: 14px;
  font-weight: bold;
}

.content {
  padding: 10px 0;
}

.consultant {
  color: #9ea7b4;
}

.b-phone {
  line-height: 26px;
  font-size: 12px;
}

h4 span {
  margin-left: 5px;
}

.side-bg {
  background: #f2f2f2;
  padding: 24px !important;
}

.return-form {
  padding: 24px;
}

.title {
  font-weight: bold;
  font-size: 16px;
  padding: 24px 0 0 24px;
}

.sky-screen {
  margin-top: 16px;
}
.remark {
  background: #eee;
  display: inline-block;
  padding: 8px 15px;
  border-radius: 8px;
  font-size: 14px;
  color: #666;
  margin-top: 10px;
}
.remark p:last-of-type {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}
.remark p span {
  margin-right: 5px;
}
.remark p span:nth-child(3) {
  color: #3399ff;
  cursor: pointer;
  margin-right: 0;
}
.remark p span:last-of-type {
  color: red;
  cursor: pointer;
  margin-right: 0;
}
.ivu-divider {
  margin: 0 5px;
  background-color: #ccc;
}
.pizhu {
  color: #3399ff;
  cursor: pointer;
  margin-left: 50px;
}
</style>
